package cake.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cake.bean.Message;
import cake.db.MySqlDb;

public class MessageDao {
	private MySqlDb db=new MySqlDb();
	
	//获取留言
	public Message getMessage(long id)
	{
		Message msg=null;
		String sql="select * from message where id="+id;
		try {
			ResultSet rs = db.query(sql);
			while(rs.next())
			{
				msg=new Message();
				msg.setId(rs.getLong("id"));
				msg.setContent(rs.getString("content"));
				msg.setOccurTime(rs.getString("occurTime"));
				msg.setUserid(rs.getLong("userid"));
				break;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally
		{
			db.Close();
		}
		
		return msg;
	}
	
	/**
	 * 获取留言列表
	 * @param currPage 当前页
	 * @param pageSize	页大小
	 * @param where		条件
	 * @return
	 */
	public List<Message> getMessages(int currPage,int pageSize,String where)
	{
		List<Message> msgs=new ArrayList<Message>();
		String sql="select * from message ";
		if(!where.equals(""))
		{
			sql+=" Where "+where;
		}
		if(pageSize!=0)
		{
			sql+=" limit "+((currPage-1)*pageSize)+","+pageSize;
		}
		try {
			ResultSet rs = db.query(sql);
			while(rs.next())
			{
				Message msg=new Message();
				msg.setId(rs.getLong("id"));
				msg.setContent(rs.getString("content"));
				msg.setOccurTime(rs.getString("occurTime"));
				msg.setUserid(rs.getLong("userid"));
				
				msgs.add(msg);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally
		{
			db.Close();
		}
		
		return msgs;
	}
	/**
	 * 添加留言	
	 * @param Message
	 * @return
	 */
	public boolean addMessage(Message msg)
	{
		String sql="insert into message(userid,content,occurTime) values("+msg.getUserid()+",'"+msg.getContent()+"','"+msg.getOccurTime()+"')";
		try
		{
			int row = db.execute(sql);
			
			return row>0?true:false;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}finally
		{
			db.Close();
		}
		return false;
		
	}

	/**
	 * 删除留言
	 * @param Message
	 * @return
	 */
	public  boolean deleteMessage(Message msg)
	{
		Message oldMsg=getMessage(msg.getId());
		
		if(oldMsg==null)
		{
			return false;
		}
		
		String sql="Delete from message where id="+msg.getId();
		
		try
		{
			int row = db.execute(sql);
			
			return row>0?true:false;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}finally
		{
			db.Close();
		}
		return false;
	}
}
